//
//  TTSQLManager.swift
//  TTWeibo
//
//  Created by 陶宏路 on 16/8/1.
//  Copyright © 2016年 陶路路. All rights reserved.
//

import UIKit

private let FMName = "statues.db"
class TTSQLManager: NSObject {

    static let manager:TTSQLManager = TTSQLManager()
    
    var queue:FMDatabaseQueue
    
    override init() {
        
        
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(FMName)
        
        queue = FMDatabaseQueue(path: path)
        
        super.init()
        
        createTable()
    }
    
//    创建数据库
    func createTable(){
        
        let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)
        
        let sql = try! String(contentsOfFile: path!)
        
        queue.inDatabase { (db) -> Void in
            
            let result = db.executeStatements(sql)
            
            if result {
                
                print("创建成功")
                
            }else{
                
                print("创建失败")
            }
        }
    }
    
// 查询公共方法
    
    func searchTable(sql:String)->[[String:AnyObject]]{
        
        var tempArray:[[String:AnyObject]] = [[String:AnyObject]]()
        queue.inDatabase { (db) -> Void in
            
            let result = db.executeQuery(sql, withArgumentsInArray: nil)
            
            while result.next(){
                
                var dict:[String:AnyObject] = [String:AnyObject]()
                
                for i in 0..<result.columnCount(){
                    
                    let key = result.columnNameForIndex(i)
                    let value = result.objectForColumnIndex(i)
                    
                    dict[key] = value
                    
                }
                tempArray.append(dict)
                
            }
        }
        
        return tempArray
    }
}
